package com.example.rbacmanage.controller;

import com.alibaba.druid.util.StringUtils;
import com.example.rbacmanage.annotation.CurrentUser;
import com.example.rbacmanage.annotation.PassFrontToken;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.AppUser;
import com.example.rbacmanage.service.AppUserService;
import com.example.rbacmanage.util.JwtTokenUtil;
import com.example.rbacmanage.util.PasswordUtil;
import com.example.rbacmanage.vo.WxLoginReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/app/user")
public class AppUserController {
    @Autowired
    private AppUserService appUserService;


    @PostMapping("/register")
    public Result register(@RequestBody AppUser appUser){

        AppUser b = new AppUser();
        b.setPhone(appUser.getPhone());
        Integer count = appUserService.getCount(b);
        if (count > 0){
            return Result.error("当前手机号已注册");
        }
        appUserService.register(appUser);
        return Result.success();
    }

    @PostMapping("/logout")
    public Result logout(@CurrentUser Long userId){
        return Result.success(appUserService.logout(userId));
    }

    @GetMapping("/login")
    public Result login(AppUser appUser){
        if (StringUtils.isEmpty(appUser.getPhone()) || StringUtils.isEmpty(appUser.getPassword())){
            return Result.error("账户或密码不能为空");
        }
        AppUser appUserQuery = new AppUser();
        appUserQuery.setPhone(appUser.getPhone());
        Integer count = appUserService.getCount(appUser);
        if (count == 0){
            return Result.error("账户不存在");
        }

        //密码是否正确
        AppUser databaseAppUser = appUserService.getByPhone(appUser.getPhone());
        if (!PasswordUtil.checkPassword(appUser.getPassword(), databaseAppUser.getPassword())){
            return Result.error("密码不正确");
        }

        String token = appUserService.login(databaseAppUser);
        Map<String,Object> map = new HashMap<>();
        map.put("result",token);
        map.put("expiredTime", JwtTokenUtil.getExpiredDateFromToken(token));
        return Result.success(map);
    }

    @GetMapping("/loginUserInfo")
    public Result loginUserInfo(@CurrentUser Long userId){
        AppUser appUser = appUserService.getById(userId);
        return Result.success(appUser);
    }

    @PassFrontToken
    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestBody WxLoginReq wxLoginReq){
        if (StringUtils.isEmpty(wxLoginReq.getAvatar()) || StringUtils.isEmpty(wxLoginReq.getNickName())){
            return Result.error("头像或者昵称不能为空");
        }
        return  appUserService.wxLogin(wxLoginReq);
    }
}
